package service

import (
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
	"time"
)

type PlanService interface {
	Create(req *model.PlanCreateReq) error
	Update(id uint, req *model.PlanUpdateReq) error
	Delete(id uint) error
	GetByID(id uint) (*model.Plan, error)
	List(page, pageSize int) ([]model.Plan, int64, error)
}

type planService struct {
	repo repository.PlanRepository
}

func NewPlanService(repo repository.PlanRepository) PlanService {
	return &planService{repo: repo}
}

func (s *planService) Create(req *model.PlanCreateReq) error {
	startDate, err := time.Parse("2006-01-02", req.StartDate)
	if err != nil {
		return errors.New("开始日期格式错误")
	}

	endDate, err := time.Parse("2006-01-02", req.EndDate)
	if err != nil {
		return errors.New("结束日期格式错误")
	}

	plan := &model.Plan{
		MemberID:    req.MemberID,
		CoachID:     req.CoachID,
		Name:        req.Name,
		Description: req.Description,
		Goal:        req.Goal,
		Content:     req.Content,
		StartDate:   startDate,
		EndDate:     endDate,
		Status:      1,
	}

	return s.repo.Create(plan)
}

func (s *planService) Update(id uint, req *model.PlanUpdateReq) error {
	plan, err := s.repo.GetByID(id)
	if err != nil {
		return errors.New("计划不存在")
	}

	if req.Name != "" {
		plan.Name = req.Name
	}
	if req.Description != "" {
		plan.Description = req.Description
	}
	if req.Goal != "" {
		plan.Goal = req.Goal
	}
	if req.Content != "" {
		plan.Content = req.Content
	}
	if req.Status != nil {
		plan.Status = *req.Status
	}
	if req.StartDate != "" {
		if t, err := time.Parse("2006-01-02", req.StartDate); err == nil {
			plan.StartDate = t
		}
	}
	if req.EndDate != "" {
		if t, err := time.Parse("2006-01-02", req.EndDate); err == nil {
			plan.EndDate = t
		}
	}

	return s.repo.Update(plan)
}

func (s *planService) Delete(id uint) error {
	if _, err := s.repo.GetByID(id); err != nil {
		return errors.New("计划不存在")
	}
	return s.repo.Delete(id)
}

func (s *planService) GetByID(id uint) (*model.Plan, error) {
	return s.repo.GetByID(id)
}

func (s *planService) List(page, pageSize int) ([]model.Plan, int64, error) {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	return s.repo.List(page, pageSize)
}
